package com.linkq.ipinyin.service;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linkq.core.base.BaseService;
import com.linkq.ipinyin.dao.TextDao;
import com.linkq.ipinyin.mapper.CnCharacterMapper;
import com.linkq.ipinyin.mapper.FileMapper;
import com.linkq.ipinyin.mapper.TextMapper;
import com.linkq.ipinyin.model.CnCharacter;
import com.linkq.ipinyin.model.BcFile;
import com.linkq.ipinyin.model.Text;
import com.linkq.ipinyin.utils.FileUtils;
import com.linkq.ipinyin.vo.ResultInfo;
import com.xiaoleilu.hutool.bean.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @FileName BcTextService
 * @Description
 * @Author wangpeng
 * @date 2024-11-12
 **/

@Service
@Transactional
public class TextService extends BaseService<TextDao, Text> {
    @Autowired
    private TextMapper textMapper;
    @Autowired
    private CnCharacterMapper cnCharacterMapper;
    @Autowired
    private FileMapper fileMapper;

    public List<Text> queryTextAndFile(Text text) {
        List<Text> textList = textMapper.queryBcTextAndFile(text);
        // Set<Long> textIds = textList.stream().map(BcText::getId).collect(Collectors.toSet());
        return textList;
    }

    public List<Text> queryTextByCondition(Text bcText) {
        List<Text> textList = textMapper.selectList(getWrapper(bcText));
        if (CollectionUtils.isEmpty(textList)) {
            return new ArrayList<>();
        }
        List<Integer> textIdList = textList.stream().map(Text::getId).collect(Collectors.toList());

        List<CnCharacter> characterList = cnCharacterMapper.selectList(Wrappers.<CnCharacter>lambdaQuery().in(CnCharacter::getBelongText, textIdList));
        for(Text text : textList) {
            if (StringUtils.isNotBlank(text.getPictureId())) {
                List<BcFile> fileList = fileMapper.selectList(
                        Wrappers.<BcFile>lambdaQuery().in(BcFile::getId, Arrays.asList(text.getPictureId().split(",")))
                );
                text.setPictureName(fileList.stream().map(BcFile::getSourceName).collect(Collectors.toList()));
            }
            if (!Objects.isNull(text.getVideoId())) {
                BcFile file = fileMapper.selectById(text.getVideoId());
                text.setVideoName(file == null ? "" : file.getSourceName());
            }
            text.setCharacterList(characterList.stream().filter(c -> Objects.equals(text.getId(), c.getBelongText())).collect(Collectors.toList()));

        }
        return textList;
    }

    public int add(List<MultipartFile> pictures, List<MultipartFile>  videos, Text text) {
        List<Integer> pictureIds = new ArrayList<>();
        List<Integer> videoIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(pictures)) {
            for (MultipartFile picture : pictures) {
                BcFile pictureFile = FileUtils.upload(picture);
                fileMapper.insert(pictureFile);
                pictureIds.add(pictureFile.getId());
            }
        }
        if (CollectionUtils.isNotEmpty(pictureIds)) {
            text.setPictureId(StringUtils.join(pictureIds, ","));
        }
        if (CollectionUtils.isNotEmpty(videos)) {
            for (MultipartFile video : videos) {
                BcFile videoFile = FileUtils.upload(video);
                fileMapper.insert(videoFile);
                videoIds.add(videoFile.getId());
            }
        }
        if (CollectionUtils.isNotEmpty(videoIds)) {
            text.setVideoId(StringUtils.join(videoIds, ","));
        }
        return textMapper.insert(text);
    }

    private LambdaQueryWrapper<Text> getWrapper(Text text) {
        LambdaQueryWrapper<Text> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != text.getGrade(), Text::getGrade, text.getGrade());
        wrapper.eq(StringUtils.isNotBlank(text.getUnit()), Text::getUnit, text.getUnit());
        wrapper.eq(StringUtils.isNotBlank(text.getTextType()), Text::getTextType, text.getTextType());
        wrapper.like(StringUtils.isNotBlank(text.getTitle()), Text::getTitle, text.getTitle());
        wrapper.orderByAsc(Text::getSort);
        return wrapper;
    }

    public ResultInfo delete(List<Integer> ids) {
        int row = textMapper.deleteBatchIds(ids);
        if (row > 0) {
            return ResultInfo.success(row);
        }
        return ResultInfo.error("删除失败", row);
    }

    public ResultInfo edit(List<MultipartFile> pictures, List<MultipartFile> videos, Text text) {
        Text origin = textMapper.selectById(text.getId());
        if (Objects.isNull(origin)) {
            return ResultInfo.error("课文不存在", -1);
        }
        BeanUtil.copyProperties(text, origin);
        List<Integer> pictureIds = new ArrayList<>();
        List<Integer> videoIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(pictures)) {
            for (MultipartFile picture : pictures) {
                BcFile pictureFile = FileUtils.upload(picture);
                fileMapper.insert(pictureFile);
                pictureIds.add(pictureFile.getId());
            }
        }
        if (CollectionUtils.isNotEmpty(pictureIds)) {
            origin.setPictureId(StringUtils.join(pictureIds, ","));
        }
        if (CollectionUtils.isNotEmpty(videos)) {
            for (MultipartFile video : videos) {
                BcFile videoFile = FileUtils.upload(video);
                fileMapper.insert(videoFile);
                videoIds.add(videoFile.getId());
            }
        }
        if (CollectionUtils.isNotEmpty(videoIds)) {
            origin.setVideoId(StringUtils.join(videoIds, ","));
        }
        int row = textMapper.updateById(origin);
        if (row > 0) {
            return ResultInfo.success(row);
        }
        return ResultInfo.error("编辑失败", row);
    }

    // @PostConstruct
    public void initText() {
        List<File> files = FileUtil.loopFiles("D:\\doc\\ipinyin\\text");
        List<Text> texts = textMapper.selectList(
                Wrappers.<Text>lambdaQuery()
                        .isNull(Text::getGrade)
        );
        for (Text text : texts) {
            String title = text.getTitle();
            for (File file : files) {
                String content = FileUtil.readUtf8String(file);
                JSONObject jsonObject = JSON.parseObject(content);
                jsonObject.keySet().forEach(x -> {
                    if (StringUtils.equals(x, title)) {
                        text.setGrade(Integer.parseInt(file.getName().substring(0, file.getName().indexOf("."))));
                        textMapper.updateById(text);
                    }
                });
            }
        }
    }
}
